﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net;
using System.Security.Principal;
using System.Configuration;
using Sireass.Bl.Security;
using System.Web.Security;

namespace Sireass.Asp.Util
{
	public class Security
	{
		// Create a logger for use in this class
		private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

		public static void ValidarSeguridad(HttpResponse response, IIdentity identity, Type objectType)
		{
			bool security = Convert.ToBoolean(ConfigurationManager.AppSettings["Security"]);
			if (log.IsDebugEnabled)
			{
				log.Debug("security: " + security);				
			}
			if (security)
			{
				AplicarSeguridad(response, identity, objectType);
			}
		}

		protected static void AplicarSeguridad(HttpResponse response, IIdentity identity, Type objectType)
		{
			if (log.IsDebugEnabled)
			{
				log.Debug("identity.IsAuthenticated: " + identity.IsAuthenticated);
			}
			if (identity.IsAuthenticated)
			{
				SireassIdentity id = (SireassIdentity)Csla.ApplicationContext.User.Identity;
				bool canGet = Csla.Rules.BusinessRules.HasPermission(
					Csla.Rules.AuthorizationActions.GetObject, objectType);
				if (log.IsDebugEnabled)
				{
					log.Debug("id.Name: " + id.Name);
					log.Debug("id.IdUsuario: " + id.IdUsuario);
					log.Debug("id.IdPersona: " + id.IdPersona);
					log.Debug("id.FullName: " + id.FullName);
					log.Debug("objectType: " + objectType);
					log.Debug("canGet: " + canGet);
					foreach (string rol in id.Roles)
					{
						log.Debug("rol: " + rol);
					}
				}
				if (!canGet)
				{
					response.Redirect(FormsAuthentication.DefaultUrl);
				}
			}
			else
			{
				response.Redirect(FormsAuthentication.LoginUrl);
			}
		}

	}
}